<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
    <el-form-item label="用户名称" prop="name">
      <el-input type="text" v-model="ruleForm.name"></el-input>
     {{price}}
     <el-button type="primary" @click="changePrice">改变price</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click.native="submitForm('ruleForm')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {mapState,mapMutations} from 'vuex'
export default {
  data() {
    return {
      isOk: false,
      ruleForm: {
        name: ""
      },
      rules: {
        name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      }
    };
  },
  created() {},
  watch: {
    "ruleForm.name"(newval, oldval) {
      if (newval != oldval) {
        this.isOk = false;
      }
    }
  },
  methods: {
    ...mapMutations({
      "updatePrice":'updatePrice'
    }),
    changePrice(){
      this.updatePrice(300)
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.isOk = true;
          this.$message.success("success ok!!");
        } else {
          this.$message.info("error submit!!");
          return false;
        }
      });
    },
  },
  computed: {
    ...mapState({
      price:"price"
    })
  },
  components: {},
  //路由钩子，离开前
  beforeRouteLeave(to, from, next) {
    if (!this.isOk) {
      this.$confirm("您有信息尚未保存，是否离开?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          next();
        })
        .catch(() => {});
    } else {
      next();
    }
  }
};
</script>

<style lang='less' scoped >
</style>
